package com.clss.emergencycall.utils;

import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.view.View;
import android.widget.RemoteViews;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;

import com.clss.emergencycall.R;
import com.clss.emergencycall.module.imui.util.PhoneUtil;
import com.clss.emergencycall.utils.InstallAppUtils;

/** 兼容8.0 */
public class NotificationUtils extends ContextWrapper {
    private static final String TAG = "NotificationUtils";

    private NotificationManager manager;
    public static final int NOTIFICATION_ID = 1;
    public static final int NOTIFICATION_ID_MAIN = 2;
    public static final int NOTIFICATION_ID_UPDATE = 1000;
    public static final String id = "peoplesafely";
    public static final String name = "重要通知";
    public static final String IMPORTANT_NOTICE_CHANNEL_ID = "important_notice";
    public static final String IMPORTANT_NOTICE_CHANNEL_NAME = "重要通知";
    private static NotificationUtils sNotificationUtils;

    public static NotificationUtils getInstance(Context context){
        if (sNotificationUtils == null){
            synchronized (NotificationUtils.class){
                if (sNotificationUtils == null){
                    sNotificationUtils = new NotificationUtils(context);
                }
            }
        }
        return sNotificationUtils;
    }

    private NotificationUtils(Context context){
        super(context);
    }

    public void createNotificationChannel(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(id, name, NotificationManager.IMPORTANCE_HIGH);
            getManager().createNotificationChannel(channel);
        }
    }

    private NotificationManager getManager(){
        if (manager == null){
            manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }
        return manager;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public Notification.Builder getChannelNotification(String title, String content){
        return new Notification.Builder(getApplicationContext(),id)
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(android.R.drawable.stat_notify_more)
                .setSound(null,null)
                .setAutoCancel(true);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    public Notification.Builder getChannelNotification(String title, String content, Uri soundUri){
        return new Notification.Builder(getApplicationContext(),id)
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(android.R.drawable.stat_notify_more)
                .setSound(soundUri)
                .setVibrate(new long[]{1000})
                .setAutoCancel(true);
    }

    public NotificationCompat.Builder getNotification_25(String title, String content){
        return new NotificationCompat.Builder(getApplicationContext())
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(android.R.drawable.stat_notify_more)
                .setAutoCancel(true);
    }

    public void sendNotification(String ticker, String title, String content, PendingIntent contentIntent, int icon){
        if (Build.VERSION.SDK_INT >= 26){
            createNotificationChannel();
            Notification notification = getChannelNotification
                    (title, content)
                    .setContentIntent(contentIntent)
                    .setSmallIcon(icon)
                    .setTicker(ticker)
                    .build();
            getManager().notify(222,notification);
        }else{
            PhoneUtil.mobileShake(this, 1000);
            Notification notification = getNotification_25
                    (title, content)
                    .setContentIntent(contentIntent)
                    .setSmallIcon(icon)
                    .setTicker(ticker)
                    .build();
            getManager().notify(222,notification);
        }
    }

    public void sendHasSoundNotification(String ticker, String title, String content, PendingIntent contentIntent, int icon){
        Lg.i(TAG, "---这是一条有声音的通知===");
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (Build.VERSION.SDK_INT >= 26){
            createNotificationChannel();
            Notification notification = getChannelNotification
                    (title, content, uri)
                    .setContentIntent(contentIntent)
                    .setSmallIcon(icon)
                    .setTicker(ticker)
                    .build();
            getManager().notify(222,notification);
        }else{
            PhoneUtil.mobileShake(this, 1000);
            Notification notification = getNotification_25
                    (title, content)
                    .setContentIntent(contentIntent)
                    .setSmallIcon(icon)
                    .setTicker(ticker)
                    .setSound(uri)
                    .build();
            getManager().notify(222,notification);
        }
    }

    public void sendHasSoundNotification(int notifyId, String ticker, String title, String content, PendingIntent contentIntent){
        Lg.i(TAG, "---这是一条有声音的通知===");
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        if (Build.VERSION.SDK_INT >= 26){
            createNotificationChannel();
            Notification notification = getChannelNotification
                    (title, content, uri)
                    .setContentIntent(contentIntent)
                    .setSmallIcon(R.mipmap.logo)
                    .setTicker(ticker)
                    .build();
            getManager().notify(notifyId, notification);
        }else{
            PhoneUtil.mobileShake(this, 1000);
            Notification notification = getNotification_25
                    (title, content)
                    .setContentIntent(contentIntent)
                    .setSmallIcon(R.mipmap.logo)
                    .setTicker(ticker)
                    .setSound(uri)
                    .build();
            getManager().notify(notifyId, notification);
        }
    }

    public void sendSuspendNotivication(Class<?> activityClass){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            getManager().createNotificationChannel(new NotificationChannel(
                    IMPORTANT_NOTICE_CHANNEL_ID,
                    IMPORTANT_NOTICE_CHANNEL_NAME,
                    NotificationManager.IMPORTANCE_HIGH
            ));
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, IMPORTANT_NOTICE_CHANNEL_ID);
        Intent intent = new Intent(this, activityClass);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
        builder.setContentIntent(pendingIntent);
        builder.setSmallIcon(R.mipmap.logo);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.logo));
        builder.setAutoCancel(true);
        builder.setContentTitle("这是悬浮式通知");
        builder.setContentTitle("这是悬浮式弹窗内容");
        builder.addAction(0, "忽略", PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
        builder.addAction(0, "接受", PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT));
        getManager().notify(996, builder.build());
    }

    /** 主通知单独一套  （区分通知优先级 以及是否震动响铃）*/

    private NotificationManager mainManager;
    public static final String main_id = "peoplesafely_main";
    public static final String main_name = "普通通知";

    public NotificationManager getMainManager(){
        if (mainManager == null){
            mainManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        }
        return mainManager;
    }

    public void createMainNotificationChannel(){
        if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(main_id, main_name, NotificationManager.IMPORTANCE_LOW);
            channel.setSound(null, null);
            getMainManager().createNotificationChannel(channel);
        }
    }

    public Notification getMainNotification(String ticker, String title, String content, PendingIntent contentIntent, int icon){
        RemoteViews views = new RemoteViews(getPackageName(), R.layout.nocation_remoteview_main);
        views.setTextViewText(R.id.tv_one,"公安110(使用中时,请勿关闭)");
        views.setTextColor(R.id.tv_one, ContextCompat.getColor(getBaseContext(),R.color.text_gray));
        views.setTextViewText(R.id.tv_two,"点击可查看详情");
        views.setTextColor(R.id.tv_two, ContextCompat.getColor(getBaseContext(),R.color.text_gray));

        /** 关闭键 */
//        Intent intent_cancel = new Intent(XmppService.MAIN_NOTIFICATION_ID);
//        intent_cancel.putExtra("key_code","key_close");
//        PendingIntent pending_intent_close = PendingIntent.getBroadcast(this, 132, intent_cancel, PendingIntent.FLAG_UPDATE_CURRENT);
//        views.setOnClickPendingIntent(R.id.iv_back, pending_intent_close);
        views.setOnClickPendingIntent(R.id.rl_main,contentIntent);

        if (Build.VERSION.SDK_INT>=26){
            createMainNotificationChannel();
            Notification notification = getMainChannelNotification
                    (title, content)
                    .setChannelId(main_id)
                    .setContentIntent(contentIntent)
                    .setTicker(ticker)
                    .setSmallIcon(icon)
                    .setCustomContentView(views)
                    .build();
            return notification;
        }else{
            Notification notification = getMainNotification_25
                    (title, content)
                    .setContentIntent(contentIntent)
                    .setTicker(ticker)
                    .setCustomContentView(views)
                    .build();
            return notification;
        }
    }


    @RequiresApi(api = Build.VERSION_CODES.O)
    public Notification.Builder getMainChannelNotification(String title, String content){
        return new Notification.Builder(getApplicationContext(), main_id)
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(android.R.drawable.stat_notify_more)
                .setSound(null,null)
                .setAutoCancel(true);
    }
    public NotificationCompat.Builder getMainNotification_25(String title, String content){
        return new NotificationCompat.Builder(getApplicationContext())
                .setContentTitle(title)
                .setContentText(content)
                .setSmallIcon(android.R.drawable.stat_notify_more)
                .setAutoCancel(true);
    }

    NotificationCompat.Builder cBuilder;
    public void setProgressView(String url) {
        createMainNotificationChannel();
        PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                1, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
        cBuilder = new NotificationCompat.Builder(getApplicationContext(), main_id);
        RemoteViews remoteViews = new RemoteViews(getPackageName(), R.layout.view_update_version);
        remoteViews.setViewVisibility(R.id.update_version_pb, View.VISIBLE);
        remoteViews.setViewVisibility(R.id.update_version_cancel_tv, View.VISIBLE);
        cBuilder.setWhen(System.currentTimeMillis());
        cBuilder.setAutoCancel(true);
        cBuilder.setPriority(NotificationCompat.PRIORITY_MAX);
        cBuilder.setCustomContentView(remoteViews);
        Intent cancelIntent = new Intent( NOTIFICATION_ID_UPDATE+"");
        cancelIntent.putExtra("cancel", url);
        PendingIntent closePendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 111, cancelIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        remoteViews.setOnClickPendingIntent(R.id.update_version_cancel_tv, closePendingIntent);
        remoteViews.setTextViewText(R.id.update_version_tv, "正在下载……");
        remoteViews.setProgressBar(R.id.update_version_pb, 0, 0, false);
        cBuilder.setOngoing(true);
        cBuilder.setContentIntent(pIntent);
        cBuilder.setSmallIcon(R.mipmap.logo);
        getMainManager().notify(NOTIFICATION_ID_UPDATE, cBuilder.build());
    }

    public void cancel(int id) {
        getMainManager().cancel(id);
    }

    public void downloadSuccess(Context context, String path){
        @SuppressLint("RestrictedApi") RemoteViews remoteViews = cBuilder.getContentView();
        remoteViews.setViewVisibility(R.id.update_version_pb, View.GONE);
        remoteViews.setViewVisibility(R.id.update_version_cancel_tv, View.GONE);
        remoteViews.setTextViewText(R.id.update_version_tv,"下载完成，点击安装");
        PendingIntent pIntent = PendingIntent.getActivity(context,
                111, InstallAppUtils.Companion.openFile(context, path), PendingIntent.FLAG_UPDATE_CURRENT);
        cBuilder.setContentIntent(pIntent);
        cBuilder.setCustomContentView(remoteViews);
        getMainManager().notify(NOTIFICATION_ID_UPDATE, cBuilder.build());
    }

    public void notifyProgress(String contentText, int max, int progress){
        @SuppressLint("RestrictedApi") RemoteViews remoteViews = cBuilder.getContentView();
        remoteViews.setViewVisibility(R.id.update_version_pb, View.VISIBLE);
        remoteViews.setViewVisibility(R.id.update_version_cancel_tv, View.VISIBLE);
        remoteViews.setProgressBar(R.id.update_version_pb,max, progress, false);
        remoteViews.setTextViewText(R.id.update_version_tv,contentText);
        cBuilder.setCustomContentView(remoteViews);
        getMainManager().notify(NOTIFICATION_ID_UPDATE, cBuilder.build());
    }

    public void downloadFail(){
        @SuppressLint("RestrictedApi") RemoteViews remoteViews = cBuilder.getContentView();
        remoteViews.setViewVisibility(R.id.update_version_pb, View.GONE);
        remoteViews.setViewVisibility(R.id.update_version_cancel_tv, View.GONE);
        remoteViews.setTextViewText(R.id.update_version_tv,"下载失败，请检查网络");
        PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(),
                111, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);
        cBuilder.setContentIntent(pIntent);
        cBuilder.setCustomContentView(remoteViews);
        getMainManager().notify(NOTIFICATION_ID_UPDATE, cBuilder.build());
    }
}
